﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;
using System.Web.Caching;
using System.ServiceModel.Activation;

namespace BackupMirthToTFS
{
    public class Global : System.Web.HttpApplication
    {
        private static CacheItemRemovedCallback OnCacheRemove = null;

        internal enum TaskToRun
        {
   
            MirthBackup
        }

        void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes(RouteTable.Routes);
            AddTask(TaskToRun.MirthBackup.ToString(), Config.RunMirthBackupCheckIntervalInSeconds);  
        }

        void RegisterRoutes(RouteCollection routes)
        {
            routes.Ignore("{resource}.axd");

            routes.MapPageRoute("MirthBackup",
                "MirthBackup/{BackupName}",
                "~/NewMirthBackup.aspx", false);    

            
            routes.MapPageRoute("Dashboard",
             "", "~/Dashboard.aspx");      
        }

         
        private void AddTask(string taskName, int seconds)
        {
            OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved);

            HttpRuntime.Cache.Insert(taskName.ToString(),
                                        seconds, null,
                                        DateTime.Now.AddSeconds(seconds), 
                                        Cache.NoSlidingExpiration,
                                        CacheItemPriority.NotRemovable, 
                                        OnCacheRemove);
        }

        private void CacheItemRemoved(string taskName, object v, CacheItemRemovedReason r)
        {
            TaskToRun task = (TaskToRun)Enum.Parse(typeof(TaskToRun), taskName);
            switch (task)
            {
                
                case TaskToRun.MirthBackup:
                    BackupMirthToTfs.RunMirthBackups();
                    break;
                default:
                    break;
            }
         

            AddTask(taskName, Convert.ToInt32(v)); // re-add our task so it recurs
        }
    }
}
